package dao

import (
	"errors"
	"github.com/wonderivan/logger"
	"strings"
	"teresa/db"
	"teresa/model"
)

var Workflow workflow

type workflow struct{}

// dao层先用到此结构体，然后是service层用到
type WorkflowResp struct {
	Items []*model.Workflow
	Total int
}

func (w *workflow) GetWorkflows(filterName, namespace string, limit, page int) (data *WorkflowResp, err error) {
	// 定义分页的起始位置
	startSet := (page - 1) * limit
	// 定义数据库查询返回的内容
	var (
		workflowList []*model.Workflow
		total        int
	)
	tx := db.GORM.
		Model(&model.Workflow{}).
		// 原来是下面这个，但是需要多个and操作，因此进行修改，否则会出现limit 1的情况
		//Where("name like ?", "%"+filterName+"%").
		Where("name like ? AND namespace = ?", "%"+filterName+"%",namespace).
		Count(&total).
		Offset(startSet).
		Order("id desc").
		Limit(limit).
		Find(&workflowList)

	// 会把空也放到error里面去。"record not found"是写死的。
	if tx.Error != nil && tx.Error.Error() != "record not found" {
		logger.Error("获取Workflow列表失败," + tx.Error.Error())
		return nil, errors.New("获取Workflow列表失败," + tx.Error.Error())
	}
	return &WorkflowResp{
		Items: workflowList,
		Total: len(workflowList),
	}, nil
}

//获取详情
func (w *workflow) GetWorkflowById(id int) (workflow *model.Workflow, err error) {
	// 这里需要实例化一个对象，就是workflow
	workflow = &model.Workflow{}
	tx := db.GORM.Where("id = ?", id).First(&workflow)
	if tx.Error != nil && tx.Error.Error() != "record not found" {
		logger.Error("获取workflow详情失败, " + tx.Error.Error())
		return nil, errors.New("获取workflow详情失败, " + tx.Error.Error())
	}
	return workflow, nil
}

//创建
func (w *workflow) CreateWorkflow(workflow *model.Workflow) (err error) {
	tx := db.GORM.Create(&workflow)
	if tx.Error != nil && tx.Error.Error() != "record not found" {
		if strings.Contains(tx.Error.Error(),"Duplicate entry") {
			logger.Error("请更换workflow名称 " + workflow.Name)
			return errors.New("请更换workflow名称 " + workflow.Name)
		}
		logger.Error("创建Workflow失败, " + tx.Error.Error())
		return errors.New("创建Workflow失败, " + tx.Error.Error())
	}
	return nil
}

// 删除
func (w *workflow) DelWorkflowById(id int) (err error) {
	// First查询，DELETE删除
	tx := db.GORM.Where("id = ?", id).Delete(&model.Workflow{})
	if tx.Error != nil && tx.Error.Error() != "record not found" {
		logger.Error("获取workflow详情失败, " + tx.Error.Error())
		return errors.New("获取workflow详情失败, " + tx.Error.Error())
	}
	return nil
}
